package com.dadovicn.auth.impl;

import com.dadovicn.auth.*;
import com.dadovicn.auth.vo.SysUserVO;
import com.dadovicn.repo.primary.auth.SysUserRepo;
import com.dadovicn.web.Result;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Resource
    private SysUserRepo sysUserRepo;

    @Override
    public List<SysUser> findBySearchTerm() {
        return null;
    }

    @Override
    public Result saveSysUser(SysUserVO sysUserVo) {
        SysUser sysUser;
        SysUserLocalAuth sysUserLocalAuth;
        if(sysUserVo.getUserId() != null) {
            sysUser = sysUserRepo.findById(sysUserVo.getUserId()).get();
            sysUserLocalAuth = sysUser.getSysUserLocalAuth();
            sysUser.setAvatarUrl("/img/av.jpg");
        } else {
            sysUser = new SysUser();
            sysUserLocalAuth = new SysUserLocalAuth();
            sysUser.setCreateTime(new Timestamp(System.currentTimeMillis()));
            sysUser.setAvatarUrl("/img/av.jpg");
            sysUserLocalAuth.setCreateTime(new Timestamp(System.currentTimeMillis()));

        }
        sysUser.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        sysUser.setUserName(sysUserVo.getUserName());
        sysUser.setRealName(sysUserVo.getRealName());
        sysUser.setGroupId(4L);
        sysUser.setStatus(true);
        sysUserLocalAuth.setPassword(genPassword(sysUserVo.getPassword()));
        sysUserLocalAuth.setSalt("salt");
        sysUserLocalAuth.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        sysUserLocalAuth.setStatus(true);
        sysUser.setSysUserLocalAuth(sysUserLocalAuth);
        sysUserRepo.save(sysUser);
        return Result.success();
    }

    @Override
    public Result updateSysUser(SysUserVO sysUserVO) {
        SysUser sysUser = sysUserRepo.findById(sysUserVO.getUserId()).get();
        sysUser.setUserName(sysUserVO.getUserName());
        SysUserLocalAuth sysUserLocalAuth = sysUser.getSysUserLocalAuth();
        sysUserLocalAuth.setPassword(genPassword(sysUserVO.getPassword()));
        sysUserLocalAuth.setSalt("salt");

        sysUserLocalAuth.setCreateTime(new Timestamp(System.currentTimeMillis()));
        sysUserLocalAuth.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        sysUserLocalAuth.setStatus(true);
        sysUser.setSysUserLocalAuth(sysUserLocalAuth);
        sysUserRepo.save(sysUser);
        return Result.success();
    }

    private String genPassword(String pwd) {
        CharSequence rawPassword = pwd;
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder.encode(rawPassword);
    }
}